package edu.ucsc.gameAI.fsm;

import java.util.Collection;
import java.util.LinkedList;

import pacman.game.Game;
import edu.ucsc.gameAI.Debug;
import edu.ucsc.gameAI.IAction;

public class StateMachine implements IStateMachine {

	IState state;

	@Override
	public Collection<IAction> update(Game game) {
		Debug.debug("Starting fsm update in state: " + state.getName(), Debug.MESSAGETYPE.STATEMENT);
		ITransition triggeredTransition = null;
		Collection<IAction> actions = new LinkedList<IAction>();

		for (ITransition trans : state.getTransitions()) {
			if (trans.isTriggered(game)) {
				triggeredTransition = trans;
				break;
			}
		}

		if (triggeredTransition != null) {
			IState targetState = triggeredTransition.getTargetState();

			if (state.getExitAction() != null)
				actions.add(state.getExitAction());
			if (triggeredTransition.getAction() != null)
				actions.add(triggeredTransition.getAction());
			if (targetState.getEntryAction() != null)
				actions.add(targetState.getEntryAction());

			Debug.debug("NEW STATE! Transitioning to: " + targetState.getName() + " " + triggeredTransition.toString(), Debug.MESSAGETYPE.STATEMENT);
			state = targetState;

			return actions;
		}

		else {
			Collection<IAction> action = new LinkedList<IAction>();
			action.add(state.getAction());
			return action;
		}

	}

	@Override
	public IState getCurrentState() {
		return state;
	}

	@Override
	public void setCurrentState(IState state) {
		this.state = state;
	}

}
